#!/usr/bin/env python 

from google.appengine.ext import webapp 
from google.appengine.ext import db

import sys 
import urllib2 
import simplejson 

import errors 
import models

class RentHandler(webapp.RequestHandler):
  def get(self, address):
    #for attr in ('stdin', 'stdout', 'stderr'):
      #setattr(sys, attr, getattr(sys, '__%s__' % attr))
    #import pdb
    #pdb.set_trace()
    geo_pt = get_geo_pt_by_address(address)
    if( isinstance(geo_pt, errors.Error) ):
      geo_pt.send(self.response)

    
def main(address, *args):
  print get_geo_pt_by_address(address)
 
def get_geo_pt_by_address(address):
  query_url = "http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false" % urllib2.quote(address)

  try:

    result = simplejson.load(urllib2.urlopen(query_url))
    if( result['status'] != "OK" or len(result['results']) == 0 ):
      return errors.error(errors.UNABLE_TO_LOCATE_PROPERTY, address)
    
    geo = result['results'][0]["geometry"]["location"]
    return db.GeoPt(geo["lat"], geo["lng"])
  except urllib2.URLError, e:
    return errors.error(errors.SERVICE_UNAVAILABLE, e.reason, 503)
  print query_url

def handle_error(e):
  print e

if (__name__ == '__main__'): main(*sys.argv)
